function Results(resultArray, mapCanvas, placeInput){
  this.resultArray = resultArray;
  this.openedInfoBoxResultId = "";
  /*Creates a the map*/
  this.createMap = function(lat, lon){
    var myLatLng = new google.maps.LatLng(lat, lon);
    var mapOptions = {
        center: myLatLng,
        zoom: 13
      };
    var map = new google.maps.Map(mapCanvas, mapOptions); 
    return map;
  };
 
  this.createMarkers = function(resultArray, map){
    debugger;
    var markers = {};
    for(var i in resultArray){
      if(!resultArray.hasOwnProperty(i)){
        continue;
      }
      var myLatLng = new google.maps.LatLng(resultArray[i].position.latitude, resultArray[i].position.longitude);
      var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        anchorPoint: new google.maps.Point(0, -29)
      });
      marker.setIcon(/** @type {google.maps.Icon} */({
      url: resultArray[i].iconImage.path,
      size: new google.maps.Size(resultArray[i].iconImage.width, resultArray[i].iconImage.height),
      origin: new google.maps.Point(0, 0),
      anchor: new google.maps.Point(17, 34),
      scaledSize: new google.maps.Size(resultArray[i].iconImage.scaledWidth, resultArray[i].iconImage.scaledHeight)
      }));
      marker.setVisible(true);
      markers[resultArray[i].id] = marker;
      resultArray[i].marker = marker;
      resultArray[i].infoWindow = new InfoBox({
         content: resultArray[i].infoWindowString,
         disableAutoPan: false,
         maxWidth: resultArray[i].infoWindowData.width,
         pixelOffset: new google.maps.Size(resultArray[i].infoWindowData.pixelOffset.x, resultArray[i].infoWindowData.pixelOffset.y),
         //pixelOffset: new google.maps.Size(0, 0),
         zIndex: null,
         boxStyle: {},
        closeBoxMargin: "",
        closeBoxURL: "",
        infoBoxClearance: new google.maps.Size(1, 1)
    });
    var infobox = resultArray[i].infoWindow;
    var thisObj = this;
    var openInfoBox = function(i) {
        thisObj.closeInfoBox();
        var m = resultArray[i].marker;
        debugger;
        resultArray[i].infoWindow.open(map, m);
        m.setVisible(false);
        thisObj.openedInfoBoxResultId = i;
    };
    var addEvent = function(i){
      google.maps.event.addListener(resultArray[i].marker, 'click', function(){openInfoBox(i);});
    };

    addEvent(i);
    }
    return markers;
  };

  this.createClusters = function(markers, map){
    var mcOptions = {gridSize: 50, maxZoom: 15};
    var markersArray = [];
    for(var key in markers){
      var i = 0;
      if(markers.hasOwnProperty(key)){
        markersArray[i++] = markers[key];
      }
    }
    var mc = new MarkerClusterer(map, markers, mcOptions);
  };

  this.createAutoComplete = function(map, placeInput){
      var autocomplete = new google.maps.places.Autocomplete(placeInput);
      google.maps.event.addListener(autocomplete, 'place_changed', function() {
      var place = autocomplete.getPlace();
      if (!place.geometry) {
        return;
      }
      // If the place has a geometry, then present it on a map.
      if (place.geometry.viewport) {
        map.fitBounds(place.geometry.viewport);
      } else {
        map.setCenter(place.geometry.location);
        map.setZoom(17);  // Why 17? Because it looks good.
      }
      var marker = new google.maps.Marker({
        position: null,
        map: map,
        anchorPoint: new google.maps.Point(0, -29)
      });
      marker.setIcon(/** @type {google.maps.Icon} */({
        url: "img/marker.png",
        size: new google.maps.Size(30, 54),
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(13, 24),
        scaledSize: new google.maps.Size(13, 24)
      }));
      marker.setPosition(place.geometry.location);
      marker.setVisible(true);

      var address = '';
      if (place.address_components) {
        address = [
          (place.address_components[0] && place.address_components[0].short_name || ''),
          (place.address_components[1] && place.address_components[1].short_name || ''),
          (place.address_components[2] && place.address_components[2].short_name || '')
        ].join(' ');
      }

      infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
      infowindow.open(map, marker);
    });
    return this.autocomplete;
  };

  this.goTo = function(lat, lon, map, markerId){
    debugger;
    var latlon = new google.maps.LatLng(lat, lon);
    var thisObj = this;
    map.setCenter(latlon);
  };

  this.addGoTo = function(result, map){
    var mapLinkATagId = "#"+result.mapLinkId;
    var thisObj = this;
    $(mapLinkATagId).click(function(){thisObj.goTo(result.position.latitude, result.position.longitude, thisObj.map, result.id);});
  };

  this.initialize = function(userLocation){
    debugger;
    this.userPosition = userLocation;
    this.map = this.createMap(this.userPosition.latitude, this.userPosition.longitude);
    var thisObj = this;
    google.maps.event.addListener(this.map, 'zoom_changed', function() {
        thisObj.closeInfoBox();
    });
    this.markers = this.createMarkers(resultArray, this.map);
    this.createClusters(this.markers, this.map);
    if(placeInput != null){
      this.createAutoComplete(this.map, placeInput);
    }
    for(var o in resultArray){
      if(!resultArray.hasOwnProperty(o)){
        continue;
      }
      this.addGoTo(resultArray[o], this.map);
    }
    var thisObj = this;
    var setUserLocation = function(pos){
      debugger;
      if(!pos){
        pos = {
          coords: {latitude: 51.524979,
          longitude: -0.129304}
        };
      }
      thisObj.userLocation = pos.coords;
      var myLatLng = new google.maps.LatLng(thisObj.userLocation.latitude, thisObj.userLocation.longitude);
      thisObj.map.setCenter(myLatLng);
    };
    if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition(function(pos){setUserLocation(pos);});
    }
  };

  this.closeInfoBox = function(){
    debugger;
    if(this.openedInfoBoxResultId === ""){
      return;
    }
    var theInfoBoxOpened = this.resultArray[this.openedInfoBoxResultId].infoWindow;
    var theMarkerHidden = this.resultArray[this.openedInfoBoxResultId].marker;
    theInfoBoxOpened.close();
    theMarkerHidden.setVisible(true);
  };
}


function load(){
  debugger;
  var id_ = 'r1';
  var result = {
  id: id_ ,
  divId: "result1",
  mapLinkId: "mapLink1",
  position: {
    latitude: 51.987417, 
    longitude: -0.184236
  },
  iconImage: {
    path: "img/marker.png",
    height:48,
    width:42,
    scaledHeight:48,
    scaledWidth:42
  },

  markerString: '',

  infoWindowString: '<div id="infoWindow_'+id_+'" class="infoWindow">'+
                    '<div class="infoWindowImage" style="background-image: url(\'../img/result1-img.jpg\');">'+
                    '</div>'+
                    '<div class="infoWindowMarkerInfo">'+
                      '<div><h4>THE HOUSE HOTEL</h4><span>&#163;39</span></div>'+
                     ' <div><p>1 bedroom, double bed.<br> Kensington, London</p></div>'+
                      '<div><a href="#">MORE INFO</a><a href="#" onclick="window.results.closeInfoBox()">X</a></div>'+
                   ' </div>'+
                  '</div>',
  infoWindowData:{
    pixelOffset:{
      x:-30,
      y: -80
    },
    width:210
  }
};
  id_ = 'r2';
  var result2 = {
  
  id: id_,
  divId: "result2",
  mapLinkId: "mapLink1",
  position: {
    latitude: 51.987417, 
    longitude: -0.194245
  },
  iconImage: {
    path: "img/marker.png",
    height:48,
    width:42,
    scaledHeight:48,
    scaledWidth:42
  },
  markerString: '',
  infoWindowString: '<div id="infoWindow_'+id_+'" class="infoWindow">'+
                    '<div class="infoWindowImage" style="background-image: url(\'img/result1-img.jpg\');">'+
                    '</div>'+
                    '<div class="infoWindowMarkerInfo">'+
                      '<div><h4>THE HOUSE HOTEL</h4><span>&#163;39</span></div>'+
                     ' <div><p>1 bedroom, double bed.<br> Kensington, London</p></div>'+
                      '<div><a href="#">MORE INFO</a><a href="#" onclick="window.results.closeInfoBox()">X</a></div>'+
                   ' </div>'+
                  '</div>',
  infoWindowData:{
    pixelOffset:{
      x:-30,
      y: -80
    },
    width:210
  }
};

id_ = 'r3';
  var result3 = {
  
  id: id_,
  divId: "result3",
  mapLinkId: "mapLink3",
  position: {
    latitude: 51.657417, 
    longitude: -0.184245
  },
  iconImage: {
    path: "img/marker.png",
    height:48,
    width:42,
    scaledHeight:48,
    scaledWidth:42
  },
  markerString: '',
  infoWindowString: '<div class="infoWindow2">'+
   ' <div class="imageContainer" style="background-image: url(\'img/result1-img.jpg\')">'+
    '</div>'+
    '<div class="infoWindowContents">'+
     ' <div class="i-w-headingContainer">'+
      '  <p class="i-w-headingTitle">THE HOUSE HOTEL</p><p class="i-w-price">&#163;39</p>'+
     ' </div>'+
     ' <div class="i-w-body">'+
      '  <p>1 bedroom.<br>London</p>'+
     ' </div>'+
      '<div class="i-w-links">'+
        '<a class="moreInfoLink" href="#">MORE INFO</a><a class="closeLink" href="#" onclick="window.results.closeInfoBox()">X</a>'+
      '</div>'+
   ' </div>'+
   ' <div class="i-w-pin">'+
   '   <div>'+
        ' </div>'+
         '<div>'+
         '</div>'+
       '</div>'+
     '</div>',
  infoWindowData:{
    pixelOffset:{
      x:-30,
      y: -80
    },
    width:250
  }
};
var resultArray = {};
resultArray[result.id] = result;
resultArray[result2.id] = result2;
resultArray[result3.id] = result3;
var userLocation = {
  latitude: 51.524979,
  longitude: -0.129304
};
debugger;
 /*Retrieves the user location*/

  var mapCanvas = document.getElementById('map-canvas');
  var placeInput = document.getElementById('place-input');
  window.results = new Results(resultArray, mapCanvas, placeInput);
  results.initialize(userLocation);
  var center = results.map.getCenter();
  debugger;
}
google.maps.event.addDomListener(window, 'load', load);

function openInfoWindow(id){
  window.results.resultArray[id].infowindow.open(window.results.map, window.results.resultArray[id].marker);
  window.results.resultArray[id].markerWindow.close();
}

var clicked = false;
$(document).ready(function(){
  var minPrice=100;
  var maxPrice=2500;
  var minDistance = 0;
  var maxDistance = 100;
  var changeButtonColor = function(child){
    $(child).parent().children().each(function(){
    $(this).removeClass("blueButton2").addClass("blueButton");
    });
    $(child).addClass("blueButton2");

    if($(child).index() == 0){
      $("#arrow").css("left","150px");
    }else if($(child).index() == 1){
      $("#arrow").css("left","230px");
    }else if($(child).index() == 2){
      $("#arrow").css("left","310px");
    }else if($(child).index() == 3){
      $("#arrow").css("left","390px");
    }
  };
  var showFilters = function(){
    $("#arrow").slideDown(0);
    $("#menu").slideDown(200);
   };
   var hideFilters = function(){
    if ((!$("#ui-datepicker-div").is(":visible") || $("#ui-datepicker-div").html() == "") && $("#n")) {
       $("#menu").slideUp(200);
       $("#arrow").slideUp(200);
    }
   };
   var changePriceValue = function(inputRange, inputTextPriceValueID){
      var inputRangeValue = parseInt($(inputRange).val());
      $(inputTextPriceValueID).removeAttr('readonly');
      $(inputTextPriceValueID).val("£"+(minPrice + maxPrice * (inputRangeValue/100)).toFixed(0));
      $(inputTextPriceValueID).attr('readonly','readonly');
   };

  $("#left-buttons-container").children().each(function (){
    $(this).click(function(){changeButtonColor($(this));
    });
  });
  function displayOrCloseMenu(){
    if(clicked == false){
      $("#controller1 > div > span:first-child").html("CLOSE");
      $("#controller1 > div > span:first-child").addClass("closeClass");
      $("#search-button-container").css("background-image","url('img/search_icon_black.png')");
      $("#search-button-container").css("position","relative");
      $("#search-button-container").css("bottom","-4px");
      showFilters();
      clicked = true;
    }else{
      $("#controller1 > div > span:first-child").html("SEARCH");
      $("#controller1 > div > span:first-child").removeClass("closeClass");
      $("#search-button-container").css("background-image","url('img/search_icon.png')");
      $("#search-button-container").css("bottom","0");
      hideFilters();
      clicked = false;
    }
  }
  $("#search-button-container").click(displayOrCloseMenu);
  $("#search-text").click(displayOrCloseMenu);
  $("#date input[type='text']").each(function(){$(this).datepicker({  
            inline: true,  
            showOtherMonths: true,  
            dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],  
        });});

  var initialPriceValue = parseInt($("#input-range-price").val());
  $("#input-range-price + p").width(170*(initialPriceValue/100));
  $("#priceValue").attr("value","£"+(minPrice + maxPrice * (initialPriceValue/100)));
  $("#priceValue").attr('readonly','readonly');
  $("#input-range-price").on("input change", function(){
    changePriceValue($(this), "#priceValue");
  });

  $("#all").change(function(){
    if($("#all").prop('checked') == true){
        $("#menu input[type='checkbox']").each(function(){
          $(this).prop('checked', true);
        });
    }else{
        $("#menu input[type='checkbox']").each(function(){
          $(this).prop('checked', false);
        });
    }
  });

  $('input[type="range"]').change(function () {
    var val = ($(this).val() - $(this).attr('min')) / ($(this).attr('max') - $(this).attr('min'));
    
    $(this).css('background-image',
                '-webkit-gradient(linear, left top, right top, '
                + 'color-stop(' + val + ', black), '
                + 'color-stop(' + val + ', #979797)'
                + ')'
                );
    $(this).css('background-image',
                '-moz-linear-gradient(left, '
                + 'black ' + (val*100) + '%, '
                + '#979797 ' + 0 + '%'
                + ')'
                );
    $(this).css('background-image',
                '-ms-linear-gradient(left, '
                + 'black ' + (val*100) + '%, '
                + '#979797 ' + 0 + '%'
                + ')'
                );
});
$("#moreInfoButton").click(function(){
  if(parseInt($("#moreInfoPanel").css('left'),10) == 1300){
    $("#moreInfoPanel").css('left',"640px");
    $("#moreInfoButton").html("CLOSE");
    $("#moreInfoPanel > div").css("display","block");
    $("#moreInfoPanel > div").css("opacity", "1");

  }else{
    $("#moreInfoPanel").css('left', "1300px");
    $("#moreInfoButton").html("MORE INFO");
    $("#moreInfoPanel > div").css("display","none");
    $("#moreInfoPanel > div").css("opacity", "0");
  }
});

addGoToProfile();
  
});

function addGoToProfile(){
  if(!$("#profileButton")){
    var profileButtonString = "<a id=\"profileButton\" href=\"#\" class=\"grayButton2\">Profile</a>";
    $("#loginButton").before(profileButtonString);    
  }
  $("#profileButton").on("click", function(){
    window.location = "profile.php";
  });
}